package com.rzjm.api.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.constant.ResponseCode;
import com.rzjm.api.entity.*;
import com.rzjm.api.service.*;
import com.rzjm.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  临时项目接口
 *@Date 2018-05-10
 */
@Component
@RequestMapping("/tempro")//url:模块/资源/{}/细分
public class TemProjectController extends BaseController {

    @Resource
    private ShopService shopService;
    @Resource
    private UserService userService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private TempProjectService tempProjectService;
    @Resource
    private TempProjectUserService tempProjectUserService;
    @Resource
    private TempProjectRecordService tempProjectRecordService;
    @Resource
    private SysErrorService sysErrorService;
    @Resource
    private UserShopRelationService userShopRelationService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private UserMpService userMpService;

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址

    @Value("${web.appid_mp}")
    private String appidMp;//图片地址
    @Value("${web.secret_mp}")
    private String secretMp;//图片地址

    /** 临时项目信息
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/detail",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String tempro_num = jsonRequest.containsKey("tempro_num") ? jsonRequest.getStr("tempro_num") : "";
            int shop_id = jsonRequest.containsKey("shop_id") ? jsonRequest.getInt("shop_id") : 1;
            if(shop_id == 0){
                shop_id = 1;
            }

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业人员"),true,true);
            }

            QueryWrapper<TempProject> qw1 = new QueryWrapper<>();
            qw1.eq("shop_id",shop_id);
            qw1.eq("project_num",tempro_num);
            qw1.last("limit 1");
            TempProject tempProject = tempProjectService.getOne(qw1);
            if(tempProject==null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您终端不存在"),true,true);
            }

            Shop shop = shopService.findById(tempProject.getShopId());
            if(shop != null){
                tempProject.setShopName(shop.getShopName());
            }

            if(sysUser.getUserType() >= 4){
                if(sysUser.getShopId() != tempProject.getShopId()){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该临时项目不属于您的企业"),true,true);
                }
            }else if(sysUser.getUserType() == 2 || sysUser.getUserType() == 3){
                UserShopRelation relation = userShopRelationService.getRelation(shop_id,sysUser.getUserId());
                if(relation == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该临时项目不属于您的企业"),true,true);
                }
            }
            map.put("tempro",tempProject);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/detail",e);
        }
        return result;
    }

    /**
     * 添加临时项目记录
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/addCheck",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject addCheck(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id"): 0;
            //项目库id
            Integer tempro_id = jsonRequest.containsKey("tempro_id") ? jsonRequest.getInt("tempro_id") : 0;
            Integer is_over = jsonRequest.containsKey("is_over") ? jsonRequest.getInt("is_over") : 0;
            String content = jsonRequest.containsKey("content") ? jsonRequest.getStr("content") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业人员"),true,true);
            }

            TempProject tempProject = tempProjectService.getById(tempro_id);
            if(tempProject == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该项目不存在"),true,true);
            }

            boolean blIsHasThisPro = true;
            QueryWrapper<TempProjectUser> qwUser = new QueryWrapper<>();
            qwUser.eq("pro_id",tempro_id);
            qwUser.eq("user_id",user_id);
            qwUser.eq("state",3);
            qwUser.orderByAsc("id");
            qwUser.last("limit 1");
            TempProjectUser tempProjectUser = tempProjectUserService.getOne(qwUser);
            if(tempProjectUser == null){
                if(is_over == 1){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未添加该项目，不能结束"),true,true);
                }
                tempProjectUser = new TempProjectUser();
                tempProjectUser.setState(3);
                tempProjectUser.setProId(tempProject.getId());
                tempProjectUser.setShopId(tempProject.getShopId());
                tempProjectUser.setShopName(tempProject.getShopName());
                tempProjectUser.setCreateTime(new Date());
                tempProjectUser.setProjectNum(tempProject.getProjectNum());
                tempProjectUser.setProName(tempProject.getProName());
                tempProjectUser.setProIntro(tempProject.getProIntro());
                tempProjectUser.setUserId(user_id);
                tempProjectUser.setUserName(sysUser.getName());
                blIsHasThisPro= false;
            }

            int proState = tempProjectUser.getState();
            TempProjectRecord record = new TempProjectRecord();
            record.setSendUserId(user.getId());
            record.setSendUserName(sysUser.getName());
            record.setProName(tempProject.getProName());
            record.setShopId(tempProject.getShopId());
            Shop shop = shopService.findById(tempProject.getShopId());
            if(shop!=null){
                record.setShopName(shop.getShopName());
            }
            record.setCreateTime(new Date());
            record.setContent(content);
            record.setProjectId(tempro_id);
            try{
                int ret  = tempProjectRecordService.addRecord(record,is_over,tempProjectUser,blIsHasThisPro);
                if(ret > 0){
                    long record_id = record.getId();
                    if(proState == 0){//发送开始微信推送消息
                        System.out.println("开始发送消息");
                        sendWxMsg(tempProject,record,1);//发送推送消息
                        System.out.println("结束发送消息");
                    }else{
                        if(is_over == 1){//发送结束微信推送消息
                            System.out.println("开始发送消息");
                            sendWxMsg(tempProject,record,1);//发送推送消息
                            System.out.println("结束发送消息");
                        }
                    }
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"上报成功",record_id),true,false);
                }else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"上报失败"),true,true);
                }
            }catch (Exception ex){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"上报失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/addCheck",e);
        }
        return result;
    }

    private void sendWxMsg(TempProject tempProject,TempProjectRecord record,Integer template_type){
        try{
            String accessToken = wxTemplateService.getAccessToken(appidMp,secretMp, 1);
            QueryWrapper<SysUser> qw = new QueryWrapper<>();
            qw.eq("shop_id",tempProject.getShopId())
                    .and(wrapper -> wrapper.eq("user_type", 4).or().eq("user_type", 6));
            List<SysUser> sysUsers = sysUserService.list(qw);
            if(sysUsers != null && sysUsers.size() > 0){
                String ok_ids = "",error_ids = "";
                for(SysUser sysUser : sysUsers){
                    List<User> users = userService.selectListByColumn("sys_user_id",sysUser.getUserId());
                    if(users != null){
                        for (User user :users){
                            if(user != null && sysUser.getIsSendMsg() == 1 && StrUtil.isNotEmpty(user.getUnionId())){
                                WxMsgTemplate template = null;
                                if(template_type == 1){//报修
                                    template = getTemplate(tempProject,user,record.getContent());
                                }
//                                System.out.println("模板消息：" + template.toString());
                                String param = JSONUtil.parseObj(template).toString();
                                JSONObject jsonObject = WxMessage.sendMsg(accessToken,param);
                                if(jsonObject != null){
                                    int errcode = jsonObject.getInt("errcode");
                                    if(errcode == 0) {//发送成功
                                        ok_ids += user.getId()+",";
                                    }else{//发送失败
                                        error_ids += user.getId()+",";
                                    }
                                    System.out.println("jsonObject:" + jsonObject.toString());
                                }
                            }
                        }
                    }
                }
                ok_ids = StringUtil.getSplitStr(ok_ids);
                error_ids = StringUtil.getSplitStr(error_ids);
                record.setSendMsgOkIds(ok_ids);
                record.setSendMsgErrorIds(error_ids);
                tempProjectRecordService.updateById(record);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            System.out.println("发送失败" + e.getMessage());
        }
    }

    private WxMsgTemplate getTemplate(TempProject tempProject,User user,String check_result){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",1);
        UserMp userMp = userMpService.selectByUniqueColumn("unionid",user.getUnionId());
        if(userMp!=null){
            template.setTouser(userMp.getOpenid());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");
            Map<String, MsgTempData> m = new HashMap<String, MsgTempData>();

            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("管理员您好，有设备出现报修警报");
            m.put("first",first);

            //设备名称
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(tempProject.getProName());
            m.put("keyword1",keyword1);

            //设备编号
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue(tempProject.getProjectNum());
            m.put("keyword2",keyword2);

            //在线状态
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue("设备在线");
            m.put("keyword3",keyword3);

            //最后时间
            MsgTempData keyword4 = new MsgTempData();
            keyword4.setColor(wxTemplate.getFontColor());
            keyword4.setValue(DateUtil.getTime());
            m.put("keyword4",keyword4);

            //设备状态
            MsgTempData keyword5 = new MsgTempData();
            keyword5.setColor(wxTemplate.getSpicalFontColor());
            keyword5.setValue("该设备存在异常报修，请及时处理");
            m.put("keyword5",keyword5);


            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getFontColor());
            remark.setValue(check_result);
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }

    /** 临时项目上报记录列表
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/recordlist",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject recordlist(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageindex = jsonRequest.containsKey("pageindex") ? jsonRequest.getInt("pageindex") : 1;
            int pagesize = jsonRequest.containsKey("pagesize") ? jsonRequest.getInt("pagesize") : 10;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }
            List<TempProjectRecord> list = tempProjectRecordService.getListBySysUserId(user,pageindex,pagesize);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/recordlist",e);
        }
        return result;
    }

    /** 巡检记录的图片上传
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/uploadImg",method = {RequestMethod.POST, RequestMethod.GET},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject uploadImg(@RequestParam("record_id") int record_id, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            TempProjectRecord record = tempProjectRecordService.getById(record_id);
            if(record == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "记录不存在"), true, true);
            }
            System.out.println("record_id==" + record_id);

            String imgs = "";
            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();
                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix)) {
                                String fileName = "record_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_TEMPRO_PHOTOS;
                                        String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;

                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();

                                        imgs += img_key +",";
                                    }
                                } catch (IOException e) {
                                    result = Tools.getJson(new GsonResultBean<>(-4, "系统异常"), true, true);
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
            if(imgs.length() > 0){
                imgs = imgs.substring(0,imgs.length() - 1);
            }
            record.setImgs(imgs);
            boolean ret = tempProjectRecordService.updateById(record);
            if(ret){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功"), true, true);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "图片上传失败"), true, true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            sysErrorService.insertSelective("terminal/uploadImg",e);
        }
        return result;
    }
}
